import requests
from requests import Response

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from yat.test import macro


class CommonApi:
    def __init__(self, token):
        self.headers = None
        self.log = Logger()
        self.comm_sh = CommonSH()
        self.token = token
        self.ip = f"https://{macro.DATAKIT_HOST}:{macro.DATAKIT_PORT}"

    def delete_host(self, host_id: str) -> Response:
        """
        datakit删除服务器
        :param host_id: host_id
        :return:
        """
        api = f'/host/{host_id}'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.delete(url=url, headers=self.headers, verify=False)
        return response

    def post_host_ping(self, data: dict) -> Response:
        """
        导入服务器前，连通性测试
        :param data:json格式服务器信息，模板：
            {"privateIp":"127.0.0.1","publicIp":"127.0.0.1","port":"22","password":"123","username":"user"}
        :return:
        """
        api = '/host/ping'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        self.log.info(self.headers)
        url = self.ip + api
        self.log.info(url)
        response = requests.post(url=url, json=data, headers=self.headers, verify=False)
        return response

    def post_host(self, data: dict) -> Response:
        """
        服务器管理，新增服务器
        :param data:json格式服务器信息
        :return:
        """
        api = '/host'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.post(url=url, json=data, headers=self.headers, verify=False)
        return response

    def get_host_page(self, name: str = '', tag_ids: str = '',
                      system_os: str = '', page_num: int = 1,
                      page_size: int = 10) -> Response:
        """
        服务器管理界面，查询服务器
        :param name: 按服务器ip查询
        :param tag_ids: 按标签查询
        :param system_os: 按操作系统查询
        :param page_num: 查询第几页的服务器
        :param page_size: 每页最大服务器数量，为10的倍数
        :return: 返回状态码和查询到的服务器信息
        """
        api = f'/host/page?name={name}&tagIds={tag_ids}&os={system_os}&pageNum={page_num}&pageSize={page_size}'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.get(url=url, headers=self.headers, verify=False)
        return response

    def post_hostUser(self, data: dict) -> Response:
        """
        服务器新增用户
        :param data: json格式用户信息
        :return:
        """
        api = '/hostUser'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.post(url=url, json=data, headers=self.headers, verify=False)
        return response

    def post_jdbcDbClusterNode_ping(self, data: dict) -> Response:
        """
        添加实例时，联通性测试
        :param data:实例信息，json格式
        :return:响应结果
        """
        api = '/jdbcDbClusterNode/ping'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.post(url=url, json=data, headers=self.headers, verify=False)
        return response

    def post_jdbcDbCluster_add(self, data: dict) -> Response:
        """
        添加实例
        :param data: 实例信息，json格式
        :return:
        """
        api = '/jdbcDbCluster/add'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.post(url=url, json=data, headers=self.headers, verify=False)
        return response

    def delete_jdbcDbCluster(self, cluster_node_id: str) -> Response:
        """
        删除实例
        :param cluster_node_id: clusterNodeId
        :return:
        """
        api = f'/jdbcDbClusterNode/{cluster_node_id}'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.delete(url=url, headers=self.headers, verify=False)
        return response

    def get_jdbcDbCluster_page(self, name: str = '', ip: str = '', db_type: str = '',
                               page_num: int = 1, page_size: int = 10) -> Response:
        """
        查询实例列表
        :param name: 集群名称
        :param ip: ip地址
        :param db_type: 数据库类型
        :param page_num: 第几页
        :param page_size: 每页最大实例数
        :return:
        """
        api = f'/jdbcDbCluster/page?name={name}&&ip={ip}&type={db_type}&pageNum={page_num}&pageSize={page_size}'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.get(url=url, headers=self.headers, verify=False)
        return response

    def get_hostUser_page(self, host_id: str):
        """
        查询服务器用户列表
        :param host_id:服务器Id，hostId
        :return:
        """
        api = f'/hostUser/page/{host_id}'
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.get(url=url, headers=self.headers, verify=False)
        return response

    def post_system_plugins_uninstall(self, plugin_name: str) -> Response:
        """
        卸载插件
        :param plugin_name: 插件名
        :return:
        """
        api = f"/system/plugins/uninstall/{plugin_name}"
        self.headers = {
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.post(url=url, headers=self.headers, verify=False)
        return response

    def post_system_plugins_install(self, jar_file: str) -> Response:
        """
        安装插件
        :param jar_file:
        :return:
        """
        api = "/system/plugins/install"
        self.headers = {
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        with open(jar_file, 'rb') as file:
            files = {'file': file}
            response = requests.post(url=url, files=files, headers=self.headers, verify=False)
        return response

    def post_system_plugins_start(self, plugin_name: str) -> Response:
        """
        启动插件
        :param plugin_name: 插件名称
        :return: 响应状态码
        """
        api = f"/system/plugins/start/{plugin_name}"
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.post(url=url, headers=self.headers, verify=False)
        return response

    def post_system_plugins_stop(self, plugin_name: str) -> Response:
        """
        启动插件
        :param plugin_name: 插件名称
        :return: 响应状态码
        """
        api = f"/system/plugins/stop/{plugin_name}"
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.post(url=url, headers=self.headers, verify=False)
        return response

    def get_system_plugins_list(self, plugin_id: str = '', plugin_status: str = '') -> Response:
        """
        插件管理页面搜索功能
        :param plugin_status: 插件状态
        :param plugin_id: 插件名
        :return:
        """
        api = f"/system/plugins/list?pluginId={plugin_id}&pluginStatus={plugin_status}"
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Bearer " + self.token
        }
        url = self.ip + api
        response = requests.get(url=url, headers=self.headers, verify=False)
        return response

    def get_system_settings(self):
        """
        datakit右上角获取系统设置
        :return:
        """
        api = "/system/setting"
        url = self.ip + api
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        response = requests.get(url=url, headers=self.headers, verify=False)
        return response

    def upload_hosts(self):
        """
        :param data: 列表格式的服务器数据（需符合接口要求的字段）
        :return: 响应对象，包含状态码和响应内容
        datakit批量上传服务器
        """
        api = "/host/upload"
        url = self.ip + api
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        response = requests.post(url=url, json=data, headers=self.headers, verify=False)
        return response
    
    def invoke_File(self,file_path):
        """
        确认是否解析
        :return:
        """
        api = "/host/invokeFile"
        url = self.ip + api
        self.headers = {
            "Content-Type": "multipart/form-data",
            "Authorization": "Bearer " + self.token
        }
        with open(file_path, 'rb') as file:
            files = {'file': file}
            response = requests.post(url=url, files=files, headers=self.headers, verify=False)
        return response
    
    def get_import_plan(self):
        """
        获取导入进度
        :return:
        """
        api = "/import/plan"
        url = self.ip + api
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token
        }
        response = requests.get(url=url, headers=self.headers, verify=False)
        return response
    
    def write_server_data(
    data: list,
    file_path: str = "servers.xlsx",
    headers: list = ["序号", "服务器名称", "内网IP", ..., "备注"]
) -> str:
    try:
        wb = load_workbook(file_path)
        ws = wb.active
        last_id = ws.cell(row=ws.max_row, column=1).value
        data[0] = last_id + 1 if isinstance(last_id, int) else 1
    except FileNotFoundError:
        wb = Workbook()
        ws = wb.active
        ws.append(headers)
        data[0] = 1
    ws.append(data)
    wb.save(file_path)
    return os.path.abspath(file_path)
    